import { defineStore } from 'pinia'
// 获取路由实例
import router from '/@/router'
import { menuToRoutes } from '/@/utils/router'
import type { IUser } from './types'
import { login } from '/@/api/modules/login'

export const useUserStore = defineStore({
  id: 'user', // id必填，且需要唯一
  // state
  state: (): IUser => {
    return {
      infoData: {},
      menuList: [],
      isCollapse: false,
    }
  },
  // getters
  getters: {},
  // actions
  actions: {
    setMenuList(list: any) {
      this.menuList = list || []
    },
    async getData() {
      // 动态添加路由
      if (this.menuList) {
        const routes = await menuToRoutes(this.menuList)
        for (const route of routes) {
          router.addRoute('main', route)
        }
      }
    },
    /**
     * @memberof 登录
     */
    async loginSubmit(obj: any) {
      return new Promise((resolve, reject) => {
        login(obj)
          .then((res: any) => {
            if (res.code == 200) {
              const resData: any = res.data
              this.infoData = resData
              if (resData.menus) {
                this.setMenuList(resData.menus.jurisdictions)
              }
            }
            resolve(res)
          })
          .catch((res: any) => {
            reject(res)
          })
      })
    },
    /**
     * @memberof 设置菜单收缩
     * @param v boolean
     */
    setIsCollapse(v: boolean) {
      this.isCollapse = v
    },
    changeId(id: number) {
      this.curId = id
      this.getData()
    },
  },
  persist: {
    enabled: true, // 开启缓存  默认会存储在本地localstorage
    // storage: localStorage, // 缓存使用方式
    // paths: [], // 需要缓存键
    strategies: [
      {
        // key: 'my_project', // key可以自己定义，不填的话默认就是这个store的ID
        storage: localStorage, // storage可以填sessionStorage，localStorage
        // paths: ['userID', 'userName'],
      }, // paths是需要存储的字段，不填就是全部
    ],
  },
})
